import fitz  # PyMuPDF
from tkinter import *
from tkinter.filedialog import askopenfilename, askdirectory
from PIL import Image
import os
import argparse
import threading


def split_pdf_pages(pdf_path, output_folder, dpi=300):
    """PDF分割

    Args:
        pdf_path (str): PDF文件
        output_folder (str): 图片输出位置
        quality (int, optional): 图像质量. Defaults to 95.
        dpi (int, optional): dpi. Defaults to 300.
    """
    doc = fitz.open(pdf_path)
    image_count = 1  # 新增全局计数器

    for page_num in range(len(doc)):
        page = doc.load_page(page_num)
        pix = page.get_pixmap(dpi=dpi)

        # 图像临时路径
        temp_img_path = os.path.join(output_folder, f"p_{image_count:02d}.png")
        img_final_path = os.path.splitext(temp_img_path)[0] + ".jpg"

        # 保存为PNG临时文件
        pix.save(temp_img_path)

        # 使用PIL打开图像并进行垂直分割
        with Image.open(temp_img_path) as img:
            width, height = img.size

            # 分割左右两半
            left_img = img.crop((0, 0, width // 2, height))
            right_img = img.crop((width // 2, 0, width, height))

            # 保存为JPEG格式
            left_img.save(os.path.splitext(img_final_path)[0] + ".jpg", "JPEG")
            image_count += 1
            right_img.save(
                os.path.splitext(
                    os.path.join(output_folder, f"p_{image_count:02d}.jpg")
                )[0]
                + ".jpg",
                "JPEG",
            )
            image_count += 1

        # 删除临时PNG文件
        os.remove(temp_img_path)

    doc.close()


def main():
    parser = argparse.ArgumentParser(description="PDF 图像分割工具")
    parser.add_argument("--pdf", help="PDF 文件路径")
    parser.add_argument("--output", help="输出目录")
    args = parser.parse_args()

    def center_window(window, width, height):
        """将窗口居中显示"""
        screen_width = window.winfo_screenwidth()
        screen_height = window.winfo_screenheight()

        x = (screen_width // 2) - (width // 2)
        y = (screen_height // 2) - (height // 2)
        window.geometry(f"{width}x{height}+{x}+{y}")

    if args.pdf and args.output:
        split_pdf_pages(args.pdf, args.output)
        print("分割完成！")
    else:
        # 创建主窗口
        root = Tk()
        root.title("PDF 图像分割工具")
        # 居中显示窗口
        center_window(root, 660, 200)

        # PDF 文件选择
        Label(root, text="PDF 文件路径：").grid(row=0, column=0, padx=5, pady=5)
        pdf_entry = Entry(root, width=50)
        pdf_entry.grid(row=0, column=1, padx=5, pady=5)
        Button(
            root,
            text="浏览",
            command=lambda: pdf_entry.insert(
                0, askopenfilename(filetypes=[("PDF files", "*.pdf")])
            ),
        ).grid(row=0, column=2, padx=5, pady=5)

        # 输出目录选择
        Label(root, text="图片输出目录：").grid(row=1, column=0, padx=5, pady=5)
        output_entry = Entry(root, width=50)
        output_entry.grid(row=1, column=1, padx=5, pady=5)
        Button(
            root, text="浏览", command=lambda: output_entry.insert(0, askdirectory())
        ).grid(row=1, column=2, padx=5, pady=5)

        # 开始按钮
        def start_split():
            status_label.config(text="分割中...")
            pdf_path = pdf_entry.get()
            output_dir = output_entry.get()
            if pdf_path and output_dir:
                # 启动新线程执行耗时任务
                threading.Thread(
                    target=run_split_pdf, args=(pdf_path, output_dir)
                ).start()

        def run_split_pdf(pdf_path, output_dir):
            split_pdf_pages(pdf_path, output_dir)
            # 使用 after 方法回到主线程更新 UI
            root.after(0, lambda: status_label.config(text="分割完成！"))

        Button(root, text="开始分割", command=start_split).grid(
            row=2, column=1, padx=5, pady=10
        )

        # 状态标签
        status_label = Label(root, text="请选择文件")
        status_label.grid(row=3, column=1, padx=5, pady=5)

        # 运行主循环
        root.mainloop()


if __name__ == "__main__":
    main()
